<template>
  <div class="invoice-management">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>本月开票金额</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥{{ statistics.monthlyAmount }}</div>
            <div class="trend">
              较上月
              <span :class="statistics.monthlyTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.monthlyTrend) }}%
                <el-icon>
                  <component :is="statistics.monthlyTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待开票金额</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥{{ statistics.pendingAmount }}</div>
            <div class="count">共 {{ statistics.pendingCount }} 笔</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>已开票金额</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥{{ statistics.issuedAmount }}</div>
            <div class="count">共 {{ statistics.issuedCount }} 笔</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>发票额度</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥{{ statistics.quota }}</div>
            <div class="progress">
              <el-progress 
                :percentage="statistics.quotaPercentage" 
                :status="statistics.quotaPercentage >= 90 ? 'exception' : ''"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="发票类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option label="增值税普通发票" value="normal" />
            <el-option label="增值税专用发票" value="special" />
          </el-select>
        </el-form-item>
        <el-form-item label="发票状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="待开票" value="pending" />
            <el-option label="已开票" value="issued" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleApply">申请开票</el-button>
      <el-button type="success" @click="handleExport">导出数据</el-button>
      <el-button 
        type="danger" 
        :disabled="!selectedRows.length"
        @click="handleBatchCancel"
      >
        批量取消
      </el-button>
    </div>

    <!-- 发票列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="invoiceNo" label="发票编号" width="180" />
        <el-table-column prop="type" label="发票类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.type === 'special' ? 'danger' : 'success'">
              {{ row.type === 'special' ? '增值税专用发票' : '增值税普通发票' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="开票金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="taxAmount" label="税额" width="120">
          <template #default="{ row }">
            ¥{{ row.taxAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="发票抬头" min-width="200" />
        <el-table-column prop="taxNumber" label="税号" width="180" />
        <el-table-column prop="email" label="接收邮箱" width="180" />
        <el-table-column prop="applyTime" label="申请时间" width="180" />
        <el-table-column prop="issueTime" label="开票时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link 
              @click="handleView(row)"
              v-if="row.status === 'issued'"
            >
              查看发票
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleCancel(row)"
              v-if="row.status === 'pending'"
            >
              取消申请
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleDownload(row)"
              v-if="row.status === 'issued'"
            >
              下载发票
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 申请开票对话框 -->
    <el-dialog
      v-model="applyDialogVisible"
      title="申请开票"
      width="600px"
    >
      <el-form
        ref="applyFormRef"
        :model="applyForm"
        :rules="applyFormRules"
        label-width="100px"
      >
        <el-form-item label="发票类型" prop="type">
          <el-radio-group v-model="applyForm.type">
            <el-radio label="normal">增值税普通发票</el-radio>
            <el-radio label="special">增值税专用发票</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发票抬头" prop="title">
          <el-input v-model="applyForm.title" placeholder="请输入发票抬头" />
        </el-form-item>
        <el-form-item label="税号" prop="taxNumber">
          <el-input v-model="applyForm.taxNumber" placeholder="请输入税号" />
        </el-form-item>
        <el-form-item label="接收邮箱" prop="email">
          <el-input v-model="applyForm.email" placeholder="请输入接收邮箱" />
        </el-form-item>
        <el-form-item label="开票金额" prop="amount">
          <el-input-number
            v-model="applyForm.amount"
            :min="0"
            :precision="2"
            :step="0.01"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="applyForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="applyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleApplySubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看发票对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="发票详情"
      width="800px"
    >
      <div class="invoice-detail" v-if="currentInvoice">
        <div class="invoice-header">
          <h3>{{ currentInvoice.type === 'special' ? '增值税专用发票' : '增值税普通发票' }}</h3>
          <el-tag :type="getStatusType(currentInvoice.status)">
            {{ getStatusText(currentInvoice.status) }}
          </el-tag>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="发票编号">
            {{ currentInvoice.invoiceNo }}
          </el-descriptions-item>
          <el-descriptions-item label="开票金额">
            ¥{{ currentInvoice.amount.toFixed(2) }}
          </el-descriptions-item>
          <el-descriptions-item label="税额">
            ¥{{ currentInvoice.taxAmount.toFixed(2) }}
          </el-descriptions-item>
          <el-descriptions-item label="价税合计">
            ¥{{ (currentInvoice.amount + currentInvoice.taxAmount).toFixed(2) }}
          </el-descriptions-item>
          <el-descriptions-item label="发票抬头">
            {{ currentInvoice.title }}
          </el-descriptions-item>
          <el-descriptions-item label="税号">
            {{ currentInvoice.taxNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="接收邮箱">
            {{ currentInvoice.email }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ currentInvoice.applyTime }}
          </el-descriptions-item>
          <el-descriptions-item label="开票时间">
            {{ currentInvoice.issueTime }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ currentInvoice.remark }}
          </el-descriptions-item>
        </el-descriptions>
        <div class="invoice-preview" v-if="currentInvoice.invoiceUrl">
          <img :src="currentInvoice.invoiceUrl" alt="发票预览" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import {
  getMerchantInvoiceList,
  getMerchantInvoiceStatistics,
  applyMerchantInvoice,
  cancelMerchantInvoice,
  batchCancelMerchantInvoice,
  exportMerchantInvoiceList,
  getMerchantInvoiceDetail
} from '@/api/merchant'

// 统计数据
const statistics = reactive({
  monthlyAmount: 0,
  monthlyTrend: 0,
  pendingAmount: 0,
  pendingCount: 0,
  issuedAmount: 0,
  issuedCount: 0,
  quota: 0,
  quotaPercentage: 0
})

// 搜索表单
const searchForm = reactive({
  type: '',
  status: '',
  dateRange: []
})

// 分页
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 申请开票对话框
const applyDialogVisible = ref(false)
const applyFormRef = ref(null)
const applyForm = reactive({
  type: 'normal',
  title: '',
  taxNumber: '',
  email: '',
  amount: 0,
  remark: ''
})

// 查看发票对话框
const viewDialogVisible = ref(false)
const currentInvoice = ref(null)

// 表单验证规则
const applyFormRules = {
  type: [{ required: true, message: '请选择发票类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入发票抬头', trigger: 'blur' }],
  taxNumber: [{ required: true, message: '请输入税号', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入接收邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  amount: [{ required: true, message: '请输入开票金额', trigger: 'blur' }]
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantInvoiceStatistics()
    Object.assign(statistics, data)
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取发票列表
const getInvoiceList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1],
      page: page.current,
      size: page.size
    }
    const { data } = await getMerchantInvoiceList(params)
    tableData.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取发票列表失败:', error)
    ElMessage.error('获取发票列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getInvoiceList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  handleSearch()
}

// 选择行变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 申请开票
const handleApply = () => {
  Object.keys(applyForm).forEach(key => {
    applyForm[key] = key === 'type' ? 'normal' : ''
  })
  applyForm.amount = 0
  applyDialogVisible.value = true
}

// 提交申请
const handleApplySubmit = async () => {
  if (!applyFormRef.value) return
  
  try {
    await applyFormRef.value.validate()
    await applyMerchantInvoice(applyForm)
    ElMessage.success('申请提交成功')
    applyDialogVisible.value = false
    getInvoiceList()
    getStatistics()
  } catch (error) {
    console.error('提交申请失败:', error)
  }
}

// 查看发票
const handleView = async (row) => {
  try {
    const { data } = await getMerchantInvoiceDetail(row.id)
    currentInvoice.value = data
    viewDialogVisible.value = true
  } catch (error) {
    console.error('获取发票详情失败:', error)
    ElMessage.error('获取发票详情失败')
  }
}

// 取消申请
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确认取消该发票申请吗？', '提示', {
      type: 'warning'
    })
    await cancelMerchantInvoice(row.id)
    ElMessage.success('取消成功')
    getInvoiceList()
    getStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消申请失败:', error)
    }
  }
}

// 批量取消
const handleBatchCancel = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要取消的发票')
    return
  }
  try {
    await ElMessageBox.confirm('确认取消选中的发票申请吗？', '提示', {
      type: 'warning'
    })
    const ids = selectedRows.value.map(row => row.id)
    await batchCancelMerchantInvoice(ids)
    ElMessage.success('批量取消成功')
    getInvoiceList()
    getStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量取消失败:', error)
    }
  }
}

// 导出数据
const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    await exportMerchantInvoiceList(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 下载发票
const handleDownload = (row) => {
  window.open(row.invoiceUrl, '_blank')
}

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    issued: 'success',
    cancelled: 'info'
  }
  return map[status]
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    pending: '待开票',
    issued: '已开票',
    cancelled: '已取消'
  }
  return map[status]
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getInvoiceList()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getInvoiceList()
}

onMounted(() => {
  getStatistics()
  getInvoiceList()
})
</script>

<style lang="scss" scoped>
.invoice-management {
  padding: 20px;

  .statistics-cards {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-content {
      text-align: center;

      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 10px;
      }

      .trend {
        font-size: 14px;
        color: #909399;

        .up {
          color: #67c23a;
        }

        .down {
          color: #f56c6c;
        }
      }

      .count {
        font-size: 14px;
        color: #909399;
      }

      .progress {
        margin-top: 10px;
      }
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .invoice-detail {
    .invoice-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        margin: 0;
        font-size: 18px;
        color: #303133;
      }
    }

    .invoice-preview {
      margin-top: 20px;
      text-align: center;

      img {
        max-width: 100%;
        max-height: 400px;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 